import { useEffect, useState } from "react";
import { MacroAction, MacroList } from "../types/types.v1";
import _ from "lodash";

const emptyMacro = {
  name: "",
  type: 0,
  actions: [],
};

export type useMacroProps = {
  macroList: MacroList[];
  setMacroList: Function;
  initMacro: Function;
  createMacro: Function;
  changeMacroAction: Function;
  changeMacroName: Function;
  changeMacroType: Function;
  changeMacro: Function;
  checkName: Function;
  deleteMacro: Function;
};

function useMacro(): useMacroProps {
  const [macroList, setMacroList] = useState<MacroList[]>([]);
  const [deviceId, setDeviceId] = useState("");

  const initMacro = (deviceId: string) => {
    setDeviceId(deviceId);
    const res = localStorage.getItem("macro_" + deviceId);
    if (res) {
      const macro = JSON.parse(res);
      if (macro) {
        setMacroList(macro);
        return macro;
      }
    }
    return [];
  };

  const createMacro = (name: string) => {
    macroList.push({ ...emptyMacro, name });
    setMacroList([...macroList]);
  };

  const changeMacroAction = (index: number, actions: MacroAction[]) => {
    macroList[index].actions = actions;
    setMacroList(_.cloneDeep(macroList));
  };

  const changeMacroName = (index: number, name: string) => {
    macroList[index].name = name;
    setMacroList(_.cloneDeep(macroList));
  };

  const changeMacroType = (index: number, type: number) => {
    macroList[index].type = type;
    setMacroList(_.cloneDeep(macroList));
    return _.cloneDeep(macroList);
  };

  const changeMacro = (index: number, macro: MacroList) => {
    macroList[index] = macro;
    setMacroList(_.cloneDeep(macroList));
    return _.cloneDeep(macroList);
  };

  const deleteMacro = (index: number) => {
    macroList.splice(index, 1);
    setMacroList(_.cloneDeep(macroList));
  };

  const checkName = (name: string) => {
    return !!macroList.find((macro) => macro.name == name);
  };

  const saveMacro = (macro: MacroList[]) => {
    if (macro != undefined && macro.length > 0) {
      localStorage.setItem("macro_" + deviceId, JSON.stringify(macro));
    }
  };

  useEffect(() => {
    if (macroList && macroList.length > 0) {
      saveMacro(macroList);
    }
  }, [macroList]);

  return {
    macroList,
    setMacroList,
    initMacro,
    createMacro,
    changeMacroAction,
    changeMacroName,
    changeMacroType,
    changeMacro,
    checkName,
    deleteMacro,
  };
}

export default useMacro;
